package com.wbao.dianniu.tabstrip.fragments;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshListView;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.adapter.ChatNotifyAdapter;
import com.wbao.dianniu.data.ChatNotifyData;
import com.wbao.dianniu.fragment.LazyLoadBaseFragment;
import com.wbao.dianniu.im.ActivityHelperActivity;
import com.wbao.dianniu.im.AgentActivity;
import com.wbao.dianniu.im.AmHelperActivity;
import com.wbao.dianniu.im.DnHelperActivity;
import com.wbao.dianniu.im.JobHelperActivity;
import com.wbao.dianniu.im.KnowNoticeHelperActivity;
import com.wbao.dianniu.im.QaHelperActivity;
import com.wbao.dianniu.im.RecruitHelperActivity;
import com.wbao.dianniu.listener.IChatNotifyListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.manager.ChatNotifyManager;
import com.wbao.dianniu.update.ChatUnreadChangeManger;

import java.util.ArrayList;
import java.util.List;

/**
 * 通知
 * <p>
 * Created by yejianjun on 2018/5/26.
 */

public class NotifyFragment extends LazyLoadBaseFragment implements IChatNotifyListener, ChatUnreadChangeManger.IUnreadChangeListener {

    private ChatNotifyManager manager;

    private PullToRefreshListView pullListView;
    private ListView mListView;
    private TextView noDataTV;
    private ChatNotifyAdapter adapter;
    private List<ChatNotifyData> list = new ArrayList<>();
    private UpdateUIBroadcastReceiver broadcastReceiver;
    public static final String ACTION_UPDATEUI = "com.wbao.dianniu.action.updataNotify";


    public static NotifyFragment instance() {
        NotifyFragment view = new NotifyFragment();
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    /*@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_chat_notify, null);
        initFragmentView(view);
        initData();
        return view;
    }*/

    private void initFragmentView(View view) {
        noDataTV = (TextView) view.findViewById(R.id.no_chat_notify);
        pullListView = (PullToRefreshListView) view.findViewById(R.id.chat_notify_listview);
        pullListView.setMode(PullToRefreshBase.Mode.PULL_DOWN_TO_REFRESH);
        pullListView.setOnRefreshListener(onRefreshListener);
        mListView = pullListView.getRefreshableView();
        registerForContextMenu(mListView);

        adapter = new ChatNotifyAdapter(getContext());
        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(onItemClickListener);

    }

    AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//            Log.e("TAG", "position:" + position);
            ChatNotifyData data = list.get(position - 1);
            int _id = data.getId();
            int counts = data.getUnReadCount();
            String name = data.getName();
            switch (_id) {
                case 114:
                    intoClass(name, counts, DnHelperActivity.class);
                    break;
                case 115:   // 招聘小助手
                    intoClass(name, counts, RecruitHelperActivity.class);
                    break;
                case 116:   // 活动小助手
                    intoClass(name, counts, ActivityHelperActivity.class);
                    break;
                case 117:   // 好友通知
                    intoClass(name, counts, AgentActivity.class);
                    break;
                case 118:   // 面试通知
                    intoClass(name, counts, JobHelperActivity.class);
                    break;
                case 119:   // 问答通知
                    intoClass(name, counts, QaHelperActivity.class);
                    break;
                case 120:   // 匿名通知
                    intoClass(name, counts, AmHelperActivity.class);
                    break;
                case 121:   // 知识分享通知
                    intoClass(name, counts, KnowNoticeHelperActivity.class);
                    break;
            }
        }
    };

    private void intoClass(String name, int counts, Class cls) {
        Intent intent = new Intent();
        intent.putExtra(Const.BUNDLE_COUNT, counts);
        intent.putExtra(Const.BUNDLE_POST, name);
        intent.setClass(getActivity(), cls);
        getActivity().startActivity(intent);
    }

    PullToRefreshBase.OnRefreshListener onRefreshListener = new PullToRefreshBase.OnRefreshListener() {
        @Override
        public void onRefresh() {
            pullUpRequest();
        }
    };

    // 下来刷新数据请求
    private void pullUpRequest() {
        reqData();
    }

    private void reqData() {
        manager.chatNotify();
    }

    @Override
    public void onDestroy() {
        ChatUnreadChangeManger.getInstance().removeUnreadChangeListener(this);
        if (null != broadcastReceiver) {
            // 注销广播
            getContext().unregisterReceiver(broadcastReceiver);
        }
        super.onDestroy();
    }


    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("NotifyFragment"); //统计页面，"MainScreen"为页面名称，可自定义
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("NotifyFragment");
    }

    @Override
    public void onChatNotifyFailure(int errorCode, String errorMsg) {
        pullListView.onRefreshComplete(false, false);

    }

    @Override
    public void onChatNotifySuccess(List<ChatNotifyData> list) {
        pullListView.onRefreshComplete(false, false);
        if (null != list && list.size() != 0) {
            noDataTV.setVisibility(View.GONE);
            this.list = list;
            adapter.setData(list);
            adapter.notifyDataSetChanged();
            notifyUnreadChange();
        } else {
            noDataTV.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void unreadChange(int idType) {
        adapter.unReadChatChange(idType);
    }

    @Override
    public void addAllNotifyUnread(int counts) {

    }

    @Override
    public void minusAllNotifyUnread(int counts) {

    }

    @Override
    public void addAllChatUnread(int counts) {

    }

    @Override
    public void minusAllChatUnread(int counts) {

    }

    @Override
    public void setChatUnread(int counts) {

    }

    @Override
    public void setNofifyUnread(int counts) {

    }

    private void notifyUnreadChange() {
        int count = 0;
        for (int i = 0; i < list.size(); i++) {
            count += list.get(i).getUnReadCount();
        }
        ChatUnreadChangeManger.getInstance().setNofifyUnread(count);
    }

    /**
     * 收到广播，刷新通知列表
     */
    private class UpdateUIBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
//            Log.e("TAG", "收到广播，刷新通知列表");
            if (ACTION_UPDATEUI == intent.getAction()) {
                // 更新消息未读数
                reqData();
            }
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_chat_notify;
    }

    @Override
    protected void initView(View view) {
        initFragmentView(view);
        initManger();
    }

    private void initManger() {
        manager = new ChatNotifyManager(getContext());
        manager.addChatNotifyListener(this);
        ChatUnreadChangeManger.getInstance().addUnreadChangeListener(this);
    }


    @Override
    public void onStart() {
        super.onStart();
        if (null == broadcastReceiver) {
            // 动态注册广播
            IntentFilter filter = new IntentFilter();
            filter.addAction(ACTION_UPDATEUI);
            broadcastReceiver = new UpdateUIBroadcastReceiver();
            getContext().registerReceiver(broadcastReceiver, filter);

        }
    }

    @Override
    public void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
        reqData();
    }
}
